<template>
  <div>
    <label v-if="label">{{ label }}</label>
    <!-- 占据坑位,显示里面的子组件input -->
    <slot></slot>
    <!-- 校验错误的信息 -->
    <p v-if="error">{{ error }}</p>
  </div>
</template>

<script>
// Asyc-validator
import Schema from "async-validator";
export default {
  //接受model，rules进行校验
  inject: ["form"],
  data() {
    return {
      //error为空表示校验通过
      error: "",
    };
  },
  props: {
    label: {
      type: String,
      default: "",
    },
    prop: {
      type: String,
    },
  },
  mounted() {
    this.$on("validate", () => {
      this.validate();
    });
  },
  methods: {
    validate() {
      // 当前规则
      const rules = this.form.rules[this.prop];
      // 当前值
      const value = this.form.model[this.prop];
      // 校验描述对象 {当前的prop值对应当前的rule}
      const desc = { [this.prop]: rules };
      // 创建Schema实例
      const schema = new Schema(desc);
      //实例触发validate函数时才会触发这个return
      return schema.validate({ [this.prop]: value }, (errors) => {
        if (errors) {
          this.error = errors[0].message;
        } else {
          // 校验通过
          this.error = "";
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>